package item42;

import java.util.Arrays;
import java.util.List;

/**
 * 第42条：慎用可变参数
 */
public class Main01 {

    public static void main(String[] args) {
        String[] myArray = {"to", "too", "two"};
        List<String> homophones = Arrays.asList("to", "too", "two");
        // obsolete idiom to print an array!
        // 过时的打印数组
        System.out.println(Arrays.asList(myArray));
        int[] digits = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
        System.out.println(Arrays.asList(digits));
        // the right way to print an array
        // 打印数组正确的方法
        System.out.println(Arrays.toString(myArray));

        // 不必改造具有final数组参数的每个方法;只当确实是在数量不定的值上执行调用时才使用可变参数

    }

    static int sum(int ...args) {
        int sum = 0;
        for (int arg : args)
            sum += arg;
        return sum;
    }

    // the WRONG way to use varargs to pass one or more arguments!
    // 使用可变参数传递一个或多个参数的错误方法
    static int min(int ...args) {
        if (args.length == 0)
            throw new IllegalArgumentException("Too few arguments");
        int min = args[0];
        for (int i = 1; i < args.length; i++)
            if (args[i] < min)
                min = args[i];
        return min;
    }

    // the right way to use varargs to pass one or more arguments
    // 使用可变参数传递一个或多个参数的正确方法
    static int min(int firstArg, int ...remainingArgs) {
        int min = firstArg;
        for (int arg : remainingArgs)
            if(arg < min)
                min = arg;
        return min;
    }

    public static <T> List<T> gather(T ...args) {
        return Arrays.asList(args);
    }

}
